<template>
  <div class="notice-edit-container">
    <!-- 顶部导航 -->
    <div class="top-nav">
      <el-button @click="$router.go(-1)" type="text">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
      <h2 class="page-title">{{ isEdit ? '编辑公告' : '发布公告' }}</h2>
    </div>

    <!-- 编辑表单 -->
    <el-card class="edit-card" v-loading="loading">
      <el-form 
        :model="editForm" 
        :rules="formRules" 
        ref="editFormRef" 
        label-width="120px"
        @submit.prevent="handleSubmit"
      >
        <el-form-item label="公告类型" prop="type">
          <el-select v-model="editForm.type" placeholder="请选择公告类型" style="width: 100%">
            <el-option label="新闻" value="NEWS"></el-option>
            <el-option label="通知" value="NOTICE"></el-option>
            <el-option label="活动" value="ACTIVITY"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="标题" prop="title">
          <el-input v-model="editForm.title" placeholder="请输入公告标题"></el-input>
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <el-input 
            v-model="editForm.content" 
            type="textarea" 
            :rows="8"
            placeholder="请输入公告内容"
          ></el-input>
        </el-form-item>
        
        <!-- 地点字段：仅活动类型显示 -->
        <el-form-item v-if="editForm.type === 'ACTIVITY'" label="地点" prop="location">
          <el-input v-model="editForm.location" placeholder="请输入地点（可选）"></el-input>
        </el-form-item>
        
        <!-- 活动专属字段 -->
        <template v-if="editForm.type === 'ACTIVITY'">
          <el-form-item label="人数上限" prop="activityLimit">
            <el-input-number 
              v-model="editForm.activityLimit" 
              :min="1" 
              :max="1000"
              style="width: 100%"
            ></el-input-number>
          </el-form-item>
          
          <el-form-item label="报名截止时间" prop="signupDeadline">
            <el-date-picker
              v-model="editForm.signupDeadline"
              type="datetime"
              placeholder="选择报名截止时间"
              style="width: 100%"
            />
          </el-form-item>
          <!-- 报名链接输入框已删除 -->
        </template>
        
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="editForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注（可选）"
          ></el-input>
        </el-form-item>
        
        <!-- 附件上传（仅新闻和通知类型） -->
        <el-form-item v-if="editForm.type === 'NEWS' || editForm.type === 'NOTICE'" label="附件" prop="attachments">
          <el-upload
            action="#"
            :auto-upload="false"
            :on-change="handleAttachmentChange"
            :on-remove="handleAttachmentRemove"
            :file-list="attachmentList"
            multiple
          >
            <el-button type="primary">
              <el-icon><Plus /></el-icon>
              选择文件
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持doc、docx、pdf、xls、xlsx、ppt、pptx、txt等格式，单个文件不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="图片" prop="images">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleImageChange"
            :on-remove="handleImageRemove"
            :file-list="imageList"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">支持jpg、png、gif格式，单个文件不超过5MB</div>
        </el-form-item>
        
        <!-- 操作按钮 -->
        <el-form-item>
          <div class="form-actions">
            <el-button @click="$router.go(-1)">取消</el-button>
            <el-button type="primary" @click="saveAsDraft" :loading="saving">保存草稿</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Plus } from '@element-plus/icons-vue'
import { 
  getAnnouncementDetail, 
  publishAnnouncement, 
  apiUpdateDraft,
  apiSaveDraft,
  uploadAttachment,
  uploadImage
} from '@/api/announcement'

export default {
  name: 'NoticeEdit',
  components: {
    ArrowLeft,
    Plus
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()
    
    // 响应式数据
    const loading = ref(false)
    const saving = ref(false)
    const submitting = ref(false)
    const editFormRef = ref(null)
    const imageList = ref([])
    const attachmentList = ref([])
    
    // 表单数据
    const editForm = reactive({
      id: null,
      type: '',
      title: '',
      content: '',
      location: '',
      remark: '',
      images: '',
      activityLimit: null,
      signupDeadline: null,
      signupUrl: '',
      publisher: ''
    })
    
    // 从store获取用户信息
    const currentUser = computed(() => store.state.user.userInfo.username || 'admin')
    const userRole = computed(() => store.state.user.role || 'ADMIN')
    
    // 计算属性
    const isEdit = computed(() => !!route.params.id)
    
    // 表单验证规则
    const formRules = {
      type: [{ required: true, message: '请选择公告类型', trigger: 'change' }],
      title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
      content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
      activityLimit: [
        { 
          required: true, 
          message: '请输入人数上限', 
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (editForm.type === 'ACTIVITY' && (!value || value < 1)) {
              callback(new Error('请输入有效的人数上限'))
            } else {
              callback()
            }
          }
        }
      ],
      signupDeadline: [
        {
          required: true,
          message: '请选择报名截止时间',
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (editForm.type === 'ACTIVITY' && !value) {
              callback(new Error('请选择报名截止时间'))
            } else {
              callback()
            }
          }
        }
      ]
    }
    
    // 方法
    const loadNoticeDetail = async () => {
      if (!isEdit.value) return
      
      loading.value = true
      try {
        const response = await getAnnouncementDetail(route.params.id)
        
        if (response.code === 200) {
          const data = response.data
          Object.assign(editForm, {
            id: data.id,
            type: data.type,
            title: data.title,
            content: data.content,
            location: data.location || '',
            remark: data.remark || '',
            images: data.images || '',
            activityLimit: data.activityLimit,
            signupDeadline: data.signupDeadline ? new Date(data.signupDeadline) : null,
            signupUrl: data.signupUrl || '',
            publisher: data.publisher
          })
          
          // 处理图片列表
          if (data.images) {
            imageList.value = data.images.split(',').map((url, index) => ({
              name: `image_${index}`,
              url: url
            }))
          }
          
          // 处理附件列表
          if (data.attachments && Array.isArray(data.attachments)) {
            attachmentList.value = data.attachments.map(attachment => ({
              name: attachment.name || attachment.fileName,
              url: attachment.url || attachment.fileUrl,
              size: attachment.size,
              type: attachment.type
            }))
          }
        } else {
          ElMessage.error('获取公告详情失败')
        }
      } catch (error) {
        ElMessage.error('获取公告详情失败')
      } finally {
        loading.value = false
      }
    }
    
    const handleImageChange = async (file) => {
      try {
        // 调用后端API上传图片
        const response = await uploadImage(file.raw)
        if (response.code === 200) {
          // 上传成功，添加到图片列表
          imageList.value.push({
            name: response.data.name,
            url: response.data.url,
            size: response.data.size,
            type: response.data.type
          })
          ElMessage.success('图片上传成功')
        } else {
          ElMessage.error(response.message || '图片上传失败')
        }
      } catch (error) {
        ElMessage.error('图片上传失败')
      }
    }
    
    const handleImageRemove = (file) => {
      // 图片移除处理逻辑
      const index = imageList.value.findIndex(item => item.name === file.name)
      if (index > -1) {
        imageList.value.splice(index, 1)
      }
    }
    
    const handleAttachmentChange = async (file) => {
      try {
        // 调用后端API上传文件
        const response = await uploadAttachment(file.raw)
        if (response.code === 200) {
          // 上传成功，添加到附件列表
          attachmentList.value.push({
            name: response.data.name,
            url: response.data.url,
            size: response.data.size,
            type: response.data.type
          })
          ElMessage.success('附件上传成功')
        } else {
          ElMessage.error(response.message || '附件上传失败')
        }
      } catch (error) {
        ElMessage.error('附件上传失败')
      }
    }
    
    const handleAttachmentRemove = (file) => {
      // 附件移除处理逻辑
      const index = attachmentList.value.findIndex(item => item.name === file.name)
      if (index > -1) {
        attachmentList.value.splice(index, 1)
      }
    }
    
    const saveAsDraft = async () => {
      try {
        await editFormRef.value.validate()
        
        saving.value = true
        const draftData = {
          ...editForm,
          publisher: currentUser.value,
          images: imageList.value.map(item => item.url).join(','),
          attachments: attachmentList.value.map(item => ({
            name: item.name,
            url: item.url,
            size: item.size,
            type: item.type
          }))
        }
        
        console.log('保存草稿数据:', draftData)
        console.log('是否为编辑模式:', isEdit.value)
        
        let response
        if (isEdit.value) {
          console.log('调用updateDraft API')
          response = await apiUpdateDraft(draftData)
        } else {
          console.log('调用apiSaveDraft API')
          // 调用真正的保存草稿API
          response = await apiSaveDraft(draftData)
        }
        
        console.log('API响应:', response)
        
        if (response.code === 200) {
          ElMessage.success('草稿保存成功')
          router.go(-1)
        } else {
          ElMessage.error(response.message || '保存失败')
        }
      } catch (error) {
        console.error('保存草稿失败:', error)
        if (error !== 'validation failed') {
          ElMessage.error('保存失败: ' + (error.message || error))
        }
      } finally {
        saving.value = false
      }
    }
    
    const handleSubmit = async () => {
      try {
        await editFormRef.value.validate()
        
        submitting.value = true
        const announcementData = {
          ...editForm,
          publisher: currentUser.value,
          images: imageList.value.map(item => item.url).join(','),
          attachments: attachmentList.value.map(item => ({
            name: item.name,
            url: item.url,
            size: item.size,
            type: item.type
          }))
        }
        
        let response
        if (isEdit.value) {
          // 编辑模式下，发布公告而不是更新草稿
          response = await publishAnnouncement(announcementData)
        } else {
          response = await publishAnnouncement(announcementData)
        }
        
        if (response.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '发布成功')
          router.go(-1)
        } else {
          ElMessage.error(response.message || (isEdit.value ? '更新失败' : '发布失败'))
        }
      } catch (error) {
        if (error !== 'validation failed') {
          ElMessage.error('提交失败')
        }
      } finally {
        submitting.value = false
      }
    }
    
    // 生命周期
    onMounted(() => {
      loadNoticeDetail()
    })
    
    return {
      loading,
      saving,
      submitting,
      editFormRef,
      editForm,
      formRules,
      imageList,
      attachmentList,
      currentUser,
      userRole,
      isEdit,
      
      loadNoticeDetail,
      handleImageChange,
      handleImageRemove,
      handleAttachmentChange,
      handleAttachmentRemove,
      saveAsDraft,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.notice-edit-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.top-nav {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.edit-card {
  margin-bottom: 20px;
}

.form-actions {
  display: flex;
  gap: 15px;
  justify-content: flex-end;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

@media (max-width: 768px) {
  .form-actions {
    flex-direction: column;
  }
  
  .form-actions .el-button {
    width: 100%;
  }
}
</style> 